package com.lingnan.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingnan.entity.po.ChatSession;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.Date;
import java.util.List;

@Mapper
public interface ChatSessionMapper extends BaseMapper<ChatSession> {
    @Select("SELECT * FROM chat_session WHERE chat_session.seeker_id = #{seekerId}")
    List<ChatSession> selectBySeekerId(Long seekerId);
    @Select("SELECT * FROM chat_session WHERE chat_session.hr_id= #{hrId}")
    List<ChatSession> selectByHrId(Long hrId);

    @Update("UPDATE chat_session SET last_msg = #{lastMsg}, last_msg_time = #{lastMsgTime} WHERE id = #{sessionId}")
    void updateLastMessage(@Param("sessionId") Long sessionId,
                           @Param("lastMsg") String lastMsg,
                           @Param("lastMsgTime") Date lastMsgTime);

    @Update("UPDATE chat_session " +
            "SET seeker_unread_count = CASE WHEN #{userId} = seeker_id THEN seeker_unread_count + 1 ELSE seeker_unread_count END, " +
            "    hr_unread_count = CASE WHEN #{userId} = hr_id THEN hr_unread_count + 1 ELSE hr_unread_count END, " + // 添加逗号
            "    last_msg = #{lastMsg}, " + // 确保同时更新最后消息
            "    last_msg_time = #{lastMsgTime} " + // 更新时间
            "WHERE id = #{sessionId}")
    int incrementUnreadCount(@Param("sessionId") Long sessionId,
                              @Param("userId") Long userId,
                              @Param("lastMsg") String lastMsg, // 新增参数
                              @Param("lastMsgTime") Date lastMsgTime); // 新增参数

    @Update("UPDATE chat_session " +
            "SET seeker_unread_count = CASE WHEN #{userId} = seeker_id THEN 0 ELSE seeker_unread_count END, " +
            "    hr_unread_count = CASE WHEN #{userId} = hr_id THEN 0 ELSE hr_unread_count END " +
            "WHERE id = #{sessionId}")
    void resetUnreadCount(@Param("sessionId") Long sessionId, @Param("userId") Long userId);

    @Select("SELECT * FROM chat_session WHERE seeker_id = #{seekerId} AND hr_id = #{hrId}")
    ChatSession findBySeekerIdAndHrId(@Param("seekerId") Long seekerId, @Param("hrId") Long hrId);
}